<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/1/13
 * Time: 9:27
 */

namespace app\controller\admin;
use app\model\admin\User AS model;
use app\model\admin\UserKeyword AS keywords;
use app\model\admin\UserKeyword;

class User extends Base
{
    public function list(){
        $get = input('get.');
        $where = [];
        !empty($get['realname']) && $where[] = ['realname','like','%'.$get['realname'].'%'];
        !empty($get['admin_id']) && $where[] = ['admin_id','=',$get['admin_id']];
        !empty($get['corporate_name']) && $where[] = ['corporate_name','like','%'.$get['corporate_name'].'%'];
        $list = model::where($where)
            ->where('admin_id','IN',[0,$this->user->id])
            ->order('end_time DESC')
            ->paginate(['page' => $this->page,'list_rows' => $this->size]);
        return $this->view('/admin/user_list',
            [
                'get' => $get,
                'list' => $list
            ]);
    }

    public function info($id){
        $info = model::find($id);
        $keywords = UserKeyword::where('user_id','=',$id)->select();
        return $this->view('/admin/user_info',[
            'info' => $info,
            'keywords' => $keywords,
            'select' => (new model())->status_text
        ]);
    }

    public function save(){
        $id = input('id');
        $post = input('post.');
        if (!empty($post['keyword'])){
            $keywords = $post['keyword'];
            unset($post['keyword']);
        }
        if (!empty($id)){
            $find = model::find($id);
            $find->save($post);
        }else{
            $find = model::create($post);
            $id = $find->id;
        }
        if (!empty($keywords)){
            $array = [];
            foreach ($keywords AS $key => $value)
                $array[] = array_merge(['user_id' => $id],$value);
            keywords::where('user_id',$id)->delete();
            (new keywords())->insertAll($array);
        }
        return 'OK';
    }

    public function delete($ids = []){
        model::where('id','IN',$ids)
            ->save(['delete_time' => date('Y-m-d')]);
        return redirect('/admin/user/list?page='.$this->page);
    }
}